/*
 * Copyright 2014 Cungmua, Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package cungmua.vn.kiosk.network;

import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.StatusLine;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicHeader;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.json.JSONArray;
import org.json.JSONObject;

import com.google.gson.JsonObject;

import android.content.Context;
import android.util.JsonReader;
import cungmua.vn.kiosk.db.DatabaseHandler;
import cungmua.vn.kiosk.model.DonHang;
import cungmua.vn.kiosk.model.SKU;
import cungmua.vn.kiosk.utils.AppUtils;
import cungmua.vn.kiosk.utils.Constant;
import cungmua.vn.kiosk.utils.Sharereferences;
import cungmua.vn.kiosk.utils.Utils;
import cungmua.vn.kiosk.utils.WriteLog;

/**
 * @author kelvin.nguyen
 * 
 */
public class CallServices {
	public static final int TIMEOUT = 30000;

	public static String getJsonFromUrl(String url) {
		HttpClient httpclient = new DefaultHttpClient();
		HttpResponse response;
		String responseString = null;
		try {
			response = httpclient.execute(new HttpGet(url));
			StatusLine statusLine = response.getStatusLine();
			if (statusLine.getStatusCode() == HttpStatus.SC_OK) {
				ByteArrayOutputStream out = new ByteArrayOutputStream();
				response.getEntity().writeTo(out);
				out.close();
				responseString = out.toString();
			} else {
				// Closes the connection.
				response.getEntity().getContent().close();
				throw new IOException(statusLine.getReasonPhrase());
			}
		} catch (ClientProtocolException e) {
			e.printStackTrace();
			WriteLog.d(Utils.TAG, e.getMessage());
		} catch (IOException e) {

			WriteLog.d(Utils.TAG, e.getMessage());

			e.printStackTrace();
		}
		return responseString;
	}

	public static String checkLogin(Context c, String ma_nhanvien,
			String matkhau) {
		// send registryId to server php
		String url_login = Constant.URL_CHECK_LOGIN;

		try {
			// Add parent data
			HttpParams params = new BasicHttpParams();
			HttpConnectionParams.setSoTimeout(params, TIMEOUT * 3);
			HttpConnectionParams.setConnectionTimeout(params, TIMEOUT);
			HttpClient httpclient = new DefaultHttpClient(params);
			HttpPost httppost = new HttpPost(url_login);

			List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(5);

			nameValuePairs.add(new BasicNameValuePair("UserId", ma_nhanvien));
			nameValuePairs.add(new BasicNameValuePair("Password", matkhau));
			nameValuePairs.add(new BasicNameValuePair("Version", "1"));
			nameValuePairs.add(new BasicNameValuePair("DeviceId", Utils
					.getDeviceId(c)));
			nameValuePairs.add(new BasicNameValuePair("Sign", Utils
					.md5(ma_nhanvien + matkhau + "1" + Utils.getDeviceId(c)
							+ Constant.SERVER_KEY)));

			httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

			HttpResponse response = httpclient.execute(httppost);

			BufferedReader reader = new BufferedReader(new InputStreamReader(
					response.getEntity().getContent()));

			String line = reader.readLine();

			return line;

		} catch (ClientProtocolException e) {
			e.printStackTrace();
			System.out.println(e.getMessage());
		} catch (IOException e) {
			e.printStackTrace();
			System.out.println(e.getMessage());
		} catch (Exception ex) {
			System.out.println(ex.getMessage());
		}

		return null;

	}

	public static String getDonHangs(Context c, String ma, int pageIndex,
			String token) {
		// send registryId to server php
		String url_donhang = Constant.URL_DONHANGS;

		try {
			// Add parent data
			HttpParams params = new BasicHttpParams();
			HttpConnectionParams.setSoTimeout(params, TIMEOUT * 3);
			HttpConnectionParams.setConnectionTimeout(params, TIMEOUT);
			HttpClient httpclient = new DefaultHttpClient(params);
			HttpPost httppost = new HttpPost(url_donhang);

			List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(4);

			nameValuePairs.add(new BasicNameValuePair("UserId", ma));
			nameValuePairs.add(new BasicNameValuePair("Version", String
					.valueOf(AppUtils.VERSION_CODE)));
			nameValuePairs.add(new BasicNameValuePair("DeviceId", Utils
					.getDeviceId(c)));
			nameValuePairs.add(new BasicNameValuePair("Sign", Utils.md5(ma
					+ pageIndex + AppUtils.VERSION_CODE + Utils.getDeviceId(c)
					+ token)));

			httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

			HttpResponse response = httpclient.execute(httppost);

			BufferedReader reader = new BufferedReader(new InputStreamReader(
					response.getEntity().getContent()));

			String line = reader.readLine();

			return line;

		} catch (ClientProtocolException e) {
			e.printStackTrace();
			System.out.println(e.getMessage());
		} catch (IOException e) {
			e.printStackTrace();
			System.out.println(e.getMessage());
		} catch (Exception ex) {
			System.out.println(ex.getMessage());
		}

		return null;

	}

	public static String getDonHangDetail(Context c, String userId,
			String orderId, String token) {
		// send registryId to server php
		String url_donhang = "";

		try {

			// Add parent data
			HttpParams params = new BasicHttpParams();
			HttpConnectionParams.setSoTimeout(params, TIMEOUT * 3);
			HttpConnectionParams.setConnectionTimeout(params, TIMEOUT);
			HttpClient httpclient = new DefaultHttpClient(params);
			HttpPost httppost = new HttpPost(url_donhang);

			List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(5);

			nameValuePairs.add(new BasicNameValuePair("UserId", userId));
			nameValuePairs.add(new BasicNameValuePair("OrderId", orderId));
			nameValuePairs.add(new BasicNameValuePair("Version", String
					.valueOf(AppUtils.VERSION_CODE)));
			nameValuePairs.add(new BasicNameValuePair("DeviceId", Utils
					.getDeviceId(c)));
			nameValuePairs.add(new BasicNameValuePair("Sign", Utils.md5(userId
					+ orderId + AppUtils.VERSION_CODE + Utils.getDeviceId(c)
					+ token)));

			httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

			HttpResponse response = httpclient.execute(httppost);

			BufferedReader reader = new BufferedReader(new InputStreamReader(
					response.getEntity().getContent()));

			String line = reader.readLine();

			return line;

		} catch (ClientProtocolException e) {
			e.printStackTrace();
			System.out.println(e.getMessage());
		} catch (IOException e) {
			e.printStackTrace();
			System.out.println(e.getMessage());
		} catch (Exception ex) {
			System.out.println(ex.getMessage());
		}

		return null;

	}

	public static String changePassword(Context c, String userId,
			String oldPassword, String newPassword) {

		// send registryId to server php
		String url_donhang = Constant.URL_CHANGE_PASSWORD;

		try {
			// Add parent data
			HttpParams params = new BasicHttpParams();
			HttpConnectionParams.setSoTimeout(params, TIMEOUT * 3);
			HttpConnectionParams.setConnectionTimeout(params, TIMEOUT);
			HttpClient httpclient = new DefaultHttpClient(params);
			HttpPost httppost = new HttpPost(url_donhang);

			List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(5);

			nameValuePairs.add(new BasicNameValuePair("UserId", userId));
			nameValuePairs.add(new BasicNameValuePair("OldPass", oldPassword));
			nameValuePairs.add(new BasicNameValuePair("NewPass", newPassword));
			nameValuePairs.add(new BasicNameValuePair("Version", String
					.valueOf(AppUtils.VERSION_CODE)));
			nameValuePairs.add(new BasicNameValuePair("DeviceId", Utils
					.getDeviceId(c)));
			nameValuePairs.add(new BasicNameValuePair("Sign", Utils.md5(userId
					+ oldPassword + newPassword + AppUtils.VERSION_CODE
					+ Utils.getDeviceId(c) + Sharereferences.getToken(c))));

			httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

			HttpResponse response = httpclient.execute(httppost);

			BufferedReader reader = new BufferedReader(new InputStreamReader(
					response.getEntity().getContent()));

			String line = reader.readLine();

			return line;

		} catch (ClientProtocolException e) {
			e.printStackTrace();
			System.out.println(e.getMessage());
		} catch (IOException e) {
			e.printStackTrace();
			System.out.println(e.getMessage());
		} catch (Exception ex) {
			System.out.println(ex.getMessage());
		}

		return null;

	}

	public static String BackupSigleOrder(Context c, String userId,
			String orderId, String status, String shipDate, String datePart,
			String sku) {
		// send registryId to server php
		String url_donhang = Constant.URL_BACKUP_ORDER;

		try {
			// Add parent data
			HttpParams params = new BasicHttpParams();
			HttpConnectionParams.setSoTimeout(params, TIMEOUT * 3);
			HttpConnectionParams.setConnectionTimeout(params, TIMEOUT);
			HttpClient httpclient = new DefaultHttpClient(params);
			HttpPost httppost = new HttpPost(url_donhang);

			List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(5);

			JsonObject jsonObj = new JsonObject();
			jsonObj.addProperty("OrderId", orderId);
			jsonObj.addProperty("Status", status);
			jsonObj.addProperty("ShipDate", shipDate);
			jsonObj.addProperty("DatePart", datePart);
			jsonObj.addProperty("Sku", sku);

			nameValuePairs.add(new BasicNameValuePair("UserId", userId));
			nameValuePairs.add(new BasicNameValuePair("ListOrder", jsonObj
					.toString()));
			nameValuePairs.add(new BasicNameValuePair("Version", String
					.valueOf(AppUtils.VERSION_CODE)));
			nameValuePairs.add(new BasicNameValuePair("DeviceId", Utils
					.getDeviceId(c)));
			nameValuePairs.add(new BasicNameValuePair("Sign", Utils
					.md5(Constant.BACKUPORDER + userId + jsonObj.toString()
							+ AppUtils.VERSION_CODE + Utils.getDeviceId(c)
							+ Sharereferences.getToken(c))));

			httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

			HttpResponse response = httpclient.execute(httppost);

			BufferedReader reader = new BufferedReader(new InputStreamReader(
					response.getEntity().getContent()));

			String line = reader.readLine();

			return line;

		} catch (ClientProtocolException e) {
			e.printStackTrace();
			System.out.println(e.getMessage());
		} catch (IOException e) {
			e.printStackTrace();
			System.out.println(e.getMessage());
		} catch (Exception ex) {
			System.out.println(ex.getMessage());
		}

		return null;

	}

	public static String SyncOrder(Context c, List<DonHang> donhangs) {
		// send registryId to server php
		String url_donhang = Constant.URL_SYNCHONIZE;
		DatabaseHandler db=new DatabaseHandler(c);
		try {
			// Add parent data
			HttpParams params = new BasicHttpParams();
			HttpConnectionParams.setSoTimeout(params, TIMEOUT * 3);
			HttpConnectionParams.setConnectionTimeout(params, TIMEOUT);
			HttpClient httpclient = new DefaultHttpClient(params);
			HttpPost httppost = new HttpPost(url_donhang);

			JSONArray jsonArray = new JSONArray();
			JSONObject jsonObj = new JSONObject();
			jsonObj.put("UserId", db.getAllNhanviens().get(0).getId());
			jsonObj.put("Version", String.valueOf(AppUtils.VERSION_CODE));
			jsonObj.put("DeviceId", Utils.getDeviceId(c));
			jsonObj.put(
					"Sign",
					Utils.md5(Constant.BACKUPORDER + db.getAllNhanviens().get(0).getId()
							+ jsonObj.toString() + AppUtils.VERSION_CODE
							+ Utils.getDeviceId(c)
							+ Sharereferences.getToken(c)));

			

			for (DonHang dh : donhangs) {
				JSONObject jsoReq = new JSONObject();
				jsoReq.put("OrderId", dh.getOrderId());
				jsoReq.put("Status", dh.getStatus());
				jsoReq.put("ShipDate", "");
				jsoReq.put("DatePart", "");
				// create json array for skus
				JSONArray jsonArraySKUs = new JSONArray();
				
				for (SKU sku : db.getAllSKUByOrderId(dh.getOrderId())) {
					JSONObject jsonObjSku = new JSONObject();
					jsonObjSku.put("SkuId", sku.getSkuId());
					jsonObjSku.put("AdjustQuantity", sku.getQuantity());
					jsonObjSku.put("AdjustReason", sku.getSku_why_change());
					jsonArraySKUs.put(jsonObjSku);
				}
				// add list sku to DonHang
				jsoReq.put("Skus", jsonArraySKUs);
				
				// add don hang to array
				jsonArray.put(jsoReq);
			}
			jsonObj.put("ListOrder", jsonArray);

			// Head
			httppost.addHeader(new BasicHeader("Content-Type",
					"application/json"));
			httppost.setEntity(new StringEntity(jsonObj.toString()));

			HttpResponse response = httpclient.execute(httppost);

			BufferedReader reader = new BufferedReader(new InputStreamReader(
					response.getEntity().getContent()));

			String line = reader.readLine();

			return line;

		} catch (ClientProtocolException e) {
			e.printStackTrace();
			System.out.println(e.getMessage());
		} catch (IOException e) {
			e.printStackTrace();
			System.out.println(e.getMessage());
		} catch (Exception ex) {
			System.out.println(ex.getMessage());
		}

		return null;

	}
	
	public static String finishedDonHang(Context c, String userId) {
		// send registryId to server php
		String url_donhang = Constant.URL_BACKUP_ORDER;

		try {
			// Add parent data
			HttpParams params = new BasicHttpParams();
			HttpConnectionParams.setSoTimeout(params, TIMEOUT * 3);
			HttpConnectionParams.setConnectionTimeout(params, TIMEOUT);
			HttpClient httpclient = new DefaultHttpClient(params);
			HttpPost httppost = new HttpPost(url_donhang);

			List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(5);


			nameValuePairs.add(new BasicNameValuePair("UserId", userId));
			nameValuePairs.add(new BasicNameValuePair("Version", String
					.valueOf(AppUtils.VERSION_CODE)));
			nameValuePairs.add(new BasicNameValuePair("DeviceId", Utils
					.getDeviceId(c)));
			nameValuePairs.add(new BasicNameValuePair("Sign", Utils
					.md5(Constant.FINISHEDORDER + userId
							+ AppUtils.VERSION_CODE + Utils.getDeviceId(c)
							+ Sharereferences.getToken(c))));

			httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

			HttpResponse response = httpclient.execute(httppost);

			BufferedReader reader = new BufferedReader(new InputStreamReader(
					response.getEntity().getContent()));

			String line = reader.readLine();

			return line;

		} catch (ClientProtocolException e) {
			e.printStackTrace();
			System.out.println(e.getMessage());
		} catch (IOException e) {
			e.printStackTrace();
			System.out.println(e.getMessage());
		} catch (Exception ex) {
			System.out.println(ex.getMessage());
		}

		return null;

	}
	

}
